package com.yy.micro.magic.ext.strategy.format;

import com.yy.micro.magic.core.annotation.Strategy;
import com.yy.micro.magic.core.model.RuleDescriptor;
import com.yy.micro.magic.core.model.RuntimeMetadata;
import com.yy.micro.magic.core.strategy.RuleStrategyAdapter;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Map;

@Strategy("numberFormat")
public class NumberFormatStrategy extends RuleStrategyAdapter {

    @Override
    protected void process(final RuntimeMetadata metadata) {
        Object value = metadata.getInputValue();
        if (null != value){
            RuleDescriptor rule = metadata.getRule();
            NumberFormat numberFormat = getNumberFormat(rule);
            String str = numberFormat.format(value);
            addTempResult(rule.getName(),str);
        }else {
            addResult(null);
        }

    }

    private NumberFormat getNumberFormat(RuleDescriptor rule){
        String format = rule.getFormat();
        NumberFormat numberFormat = NumberFormat.getInstance();
        DecimalFormat decimalFormat = (DecimalFormat) numberFormat;
        Map<String,String> properties = rule.getProperties();
        if (!CollectionUtils.isEmpty(properties)){
            String formatType = properties.get("formatType");
            if ("1".equals(formatType)){
                numberFormat = NumberFormat.getCurrencyInstance();
                decimalFormat = (DecimalFormat) numberFormat;
            }else if ("2".equals(formatType)){
                numberFormat = NumberFormat.getPercentInstance();
            }
            decimalFormat = (DecimalFormat) numberFormat;
            if (!StringUtils.isEmpty(format)){
                decimalFormat.applyPattern(format);
            }
            String positivePrefix = properties.get("positivePrefix");
            if (!StringUtils.isEmpty(positivePrefix)){
                decimalFormat.setPositivePrefix(positivePrefix);
            }
            String positiveSuffix = properties.get("positiveSuffix");
            if (!StringUtils.isEmpty(positiveSuffix)){
                decimalFormat.setPositiveSuffix(positiveSuffix);
            }
        }
        return decimalFormat;
    }
}
